package com.wt.struggle.goodbye.main.fragment

import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.gson.reflect.TypeToken
import com.wt.struggle.goodbye.R
import com.wt.struggle.goodbye.base.Config
import com.wt.struggle.goodbye.base.ItemClickListener
import com.wt.struggle.goodbye.base.ProV4Fragment
import com.wt.struggle.goodbye.base.Send
import com.wt.struggle.goodbye.info.FileInfo
import com.wt.struggle.goodbye.info.NetInfo
import com.wt.struggle.goodbye.info.NewsInfo
import com.wt.struggle.goodbye.info.VideoInfo
import com.wt.struggle.goodbye.main.activity.SendTieActivity
import com.wt.struggle.goodbye.main.adapter.PicAdapter
import kotlinx.android.synthetic.main.expression_layout.*

class ExpressionFragment : ProV4Fragment() {

    override fun handler(what: Int, arg1: Int, netInfo: NetInfo) {
        when (what) {
            Send.EXPRESSION_CODE -> {
                if (netInfo.code == Config.SUCCESS) {
                    val result = netInfo.dataResult
                    if (result != null && result != "" && result != "null") {
                        val arr: ArrayList<VideoInfo> =
                            gson!!.fromJson(result, object : TypeToken<ArrayList<VideoInfo>>() {}.type)
                        update(arr)
                    }

                }
            }
        }
    }

    override fun createView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.expression_layout, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initAdapter()
        getExpressionList()

    }

    var beiList = arrayListOf<VideoInfo>()

    fun update(arr: ArrayList<VideoInfo>) {
        this.beiList = arr

        val stringArr = arrayListOf<FileInfo>()

        for (temp in arr) {
            val fileInfo = FileInfo()

            fileInfo.text = temp.domainname + temp.path
            stringArr.add(fileInfo)
        }

        adapter.updateData(stringArr)


    }

    private fun getExpressionList() {
        send!!.getExpression(1, handler)
    }

    lateinit var adapter: PicAdapter
    val list = arrayListOf<FileInfo>()

    private fun initAdapter() {
        expressionRecyclerView.layoutManager = GridLayoutManager(activity!!, 6)
        adapter = PicAdapter(activity!!, list)
        adapter.code = 3
        expressionRecyclerView.adapter = adapter
        adapter.itemClickListener = object : ItemClickListener {
            override fun onItemClick(position: Int) {
                (activity as SendTieActivity).saveExpression(beiList[position])
            }

            override fun onLongClick(position: Int) {
            }

        }
    }
}